﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class Sample : MonoBehaviour {

    public Text UpdateLb;

    private void Start() {
        StartCoroutine(DoUpdateAddressadble());
    }

    IEnumerator DoUpdateAddressadble() {
        AsyncOperationHandle<IResourceLocator> initHandle = Addressables.InitializeAsync();
        yield return initHandle;

        var checkHandle = Addressables.CheckForCatalogUpdates(false);
        yield return checkHandle;
        if (checkHandle.Result.Count > 0) {
            UpdateLb.text = UpdateLb.text + "\n检测到日志变动";
            var updateHandle = Addressables.UpdateCatalogs(checkHandle.Result, false);

            yield return updateHandle;

            List<IResourceLocator> locators = updateHandle.Result;
            foreach (var locator in locators) {
                List<object> keys = new List<object>();
                keys.AddRange(locator.Keys);
                var sizeHandle = Addressables.GetDownloadSizeAsync(keys);
                yield return sizeHandle;
                long totalDownloadSize = sizeHandle.Result;
                UpdateLb.text = UpdateLb.text + "\nDownload size : " + totalDownloadSize;
                Debug.Log("download size : " + totalDownloadSize);
                if (totalDownloadSize > 0) {
                    var downloadHandle = Addressables.DownloadDependenciesAsync(keys);
                    while (!downloadHandle.IsDone) {
                        float percentage = downloadHandle.PercentComplete;
                        Debug.Log($"已下载: {percentage}");
                        UpdateLb.text = UpdateLb.text + $"\n已下载: {percentage}";
                        yield return null;
                    }
                    Debug.Log("下载完毕!");
                    UpdateLb.text = UpdateLb.text + "\n下载完毕";
                    Addressables.Release(downloadHandle);
                }
            }
            Addressables.Release(updateHandle);
        } else {
            UpdateLb.text = UpdateLb.text + "\n没有检测到更新";
        }
        Addressables.Release(checkHandle);

        LocalStatic();
        LocalNonStatic();
        RemoteStatic();
        RemoteNonStatic();
    }

    public void LocalStatic() {
        Addressables.InstantiateAsync("LocalStatic", transform);
    }

    public void LocalNonStatic() {
        Addressables.InstantiateAsync("LocalNonStatic", transform);
    }

    public void RemoteStatic() {
        Addressables.InstantiateAsync("RemoteStatic", transform);
    }

    public void RemoteNonStatic() {
        Addressables.InstantiateAsync("RemoteNonStatic", transform);
    }

}
